import { switchRole } from '@/api/base'
import NavBar from '@/components/Global/NavBar'
import type { RoleEnum } from '@/role'
import { stores } from '@/stores'
import { Checkbox, List, Toast } from 'antd-mobile'
import { observer } from 'mobx-react'
import { history } from 'umi'
import wx from 'weixin-webview-jssdk'

const Role = () => {
    const { userStore } = stores
    const roleArray = Object.entries(userStore.getRoleArr ?? {})

    const currentRole = userStore.getRoleInfo?.role_id ?? 0

    const onCheckRole = async (role: RoleEnum) => {
        if (currentRole === Number(role)) return

        Toast.show('角色切换中...')
        const { data } = await switchRole(userStore.getUserInfo!.uid, role)
        userStore.updateLoginInfo(data)
        Toast.show('角色已切换为: ' + data.role_info.name)
        if (window.__wxjs_environment !== 'miniprogram') {
            history.push('/')

            return
        }

        wx.miniProgram.postMessage({
            data: {
                type: 'checkRole',
                roleData: data,
            },
        })

        wx.miniProgram.redirectTo({
            url: '/pages/webViewPostMessage/index',
        })
    }

    return (
        <>
            <NavBar title="我的身份" />
            <List header="选择身份">
                {roleArray.map(([key, value]) => (
                    <List.Item
                        key={key}
                        arrow={false}
                        extra={Number(key) === currentRole && <Checkbox checked />}
                        onClick={() => onCheckRole((key as unknown) as RoleEnum)}
                    >
                        {value}
                    </List.Item>
                ))}
            </List>
        </>
    )
}

export default observer(Role)
